import React from 'react'
import { useSearchParams } from 'react-router-dom'
import { useAuth, useSubscription } from '../contexts/AuthProvider'
import { Button } from '../components/ui/Button'
import { Badge } from '../components/ui/Badge'
import { Progress } from '../components/ui/Progress'
import { 
  Crown, 
  Check, 
  Zap,
  ArrowRight 
} from 'lucide-react'

export function Subscription() {
  const [searchParams] = useSearchParams()
  const { userProfile } = useAuth()
  const { subscription } = useSubscription()
  const reason = searchParams.get('reason')
  const feature = searchParams.get('feature')

  const plans = [
    {
      id: 'free',
      name: 'Free',
      price: '$0',
      period: '/forever',
      description: 'Perfect for getting started',
      features: [
        '10 saved papers',
        '3 active alerts',
        'Basic search',
        'Email notifications',
        'Mobile app access'
      ],
      limitations: true
    },
    {
      id: 'premium',
      name: 'Premium',
      price: '$9.99',
      period: '/month',
      description: 'For serious researchers',
      features: [
        '1,000 saved papers',
        'Unlimited alerts',
        'Advanced search & filters',
        'Analytics dashboard',
        'Priority support',
        'API access',
        'Bulk export',
        'Custom categories'
      ],
      popular: true
    },
    {
      id: 'academic',
      name: 'Academic',
      price: '$4.99',
      period: '/month',
      description: 'Special pricing for students',
      features: [
        '500 saved papers',
        '50 active alerts',
        'Advanced search & filters',
        'Analytics dashboard',
        'Student verification required'
      ],
      academic: true
    }
  ]

  const currentPlan = userProfile?.subscription_status || 'free'

  const getUsageData = () => {
    if (!subscription) return null
    
    return {
      savedPapers: {
        current: subscription.usage_metrics?.saved_papers_count || 0,
        max: subscription.features?.max_saved_papers || 10,
        percentage: Math.min(((subscription.usage_metrics?.saved_papers_count || 0) / (subscription.features?.max_saved_papers || 10)) * 100, 100)
      },
      alerts: {
        current: subscription.usage_metrics?.active_alerts_count || 0,
        max: subscription.features?.max_alerts || 3,
        percentage: Math.min(((subscription.usage_metrics?.active_alerts_count || 0) / (subscription.features?.max_alerts || 3)) * 100, 100)
      }
    }
  }

  const usage = getUsageData()

  return (
    <div className="space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Subscription</h1>
        <p className="text-gray-600">
          Manage your plan and see your usage
        </p>
      </div>

      {/* Alert for specific reasons */}
      {reason === 'bookmark_limit' && (
        <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
          <div className="flex items-center">
            <Crown className="h-5 w-5 text-orange-600 mr-3" />
            <div>
              <h3 className="font-medium text-orange-800">Bookmark limit reached</h3>
              <p className="text-sm text-orange-700 mt-1">
                You've reached your limit of {subscription?.features?.max_saved_papers} saved papers. 
                Upgrade to save more papers to your library.
              </p>
            </div>
          </div>
        </div>
      )}

      {feature && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center">
            <Zap className="h-5 w-5 text-blue-600 mr-3" />
            <div>
              <h3 className="font-medium text-blue-800">Premium Feature</h3>
              <p className="text-sm text-blue-700 mt-1">
                {feature === 'analytics' && 'Analytics and insights are available with Premium plans.'}
                {feature === 'advanced_search' && 'Advanced search and filtering requires a Premium subscription.'}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Current Plan & Usage */}
      {currentPlan !== 'free' ? (
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center space-x-3">
              <Crown className="h-6 w-6 text-yellow-500" />
              <div>
                <h3 className="font-semibold text-gray-900 capitalize">{currentPlan} Plan</h3>
                <p className="text-sm text-gray-600">Active subscription</p>
              </div>
            </div>
            <Badge variant="success">Active</Badge>
          </div>
          
          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <div className="flex justify-between text-sm mb-1">
                <span>Saved Papers</span>
                <span>{usage?.savedPapers.current} / {usage?.savedPapers.max}</span>
              </div>
              <Progress value={usage?.savedPapers.percentage || 0} />
            </div>
            
            <div>
              <div className="flex justify-between text-sm mb-1">
                <span>Active Alerts</span>
                <span>{usage?.alerts.current} / {usage?.alerts.max}</span>
              </div>
              <Progress value={usage?.alerts.percentage || 0} />
            </div>
          </div>
        </div>
      ) : usage && (
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <h3 className="font-semibold text-gray-900 mb-4">Usage Overview</h3>
          
          <div className="space-y-4">
            <div>
              <div className="flex justify-between text-sm mb-1">
                <span>Saved Papers</span>
                <span>{usage.savedPapers.current} / {usage.savedPapers.max}</span>
              </div>
              <Progress value={usage.savedPapers.percentage} />
              {usage.savedPapers.percentage > 80 && (
                <p className="text-xs text-orange-600 mt-1">
                  You're approaching your limit. Consider upgrading for more storage.
                </p>
              )}
            </div>
            
            <div>
              <div className="flex justify-between text-sm mb-1">
                <span>Active Alerts</span>
                <span>{usage.alerts.current} / {usage.alerts.max}</span>
              </div>
              <Progress value={usage.alerts.percentage} />
            </div>
          </div>
        </div>
      )}

      {/* Plans */}
      <div>
        <h2 className="text-xl font-semibold text-gray-900 mb-6">Choose Your Plan</h2>
        
        <div className="grid md:grid-cols-3 gap-6">
          {plans.map(plan => (
            <div key={plan.id} className={`relative bg-white rounded-lg border-2 p-6 ${
              plan.popular ? 'border-blue-500' : 
              plan.id === currentPlan ? 'border-green-500' : 
              'border-gray-200'
            }`}>
              {plan.popular && (
                <div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
                  <Badge variant="default" className="px-3 py-1">Most Popular</Badge>
                </div>
              )}
              
              {plan.id === currentPlan && (
                <div className="absolute -top-3 right-4">
                  <Badge variant="success" className="px-3 py-1">Current Plan</Badge>
                </div>
              )}

              <div className="text-center mb-6">
                <h3 className="text-xl font-semibold text-gray-900 mb-2">{plan.name}</h3>
                <div className="mb-2">
                  <span className="text-4xl font-bold text-gray-900">{plan.price}</span>
                  <span className="text-gray-600">{plan.period}</span>
                </div>
                <p className="text-gray-600">{plan.description}</p>
              </div>

              <ul className="space-y-3 mb-8">
                {plan.features.map((feature, index) => (
                  <li key={index} className="flex items-start">
                    <Check className="h-4 w-4 text-green-500 mr-3 mt-0.5 flex-shrink-0" />
                    <span className="text-gray-700 text-sm">{feature}</span>
                  </li>
                ))}
              </ul>

              <Button 
                className="w-full"
                variant={plan.id === currentPlan ? 'outline' : plan.popular ? 'default' : 'outline'}
                disabled={plan.id === currentPlan}
              >
                {plan.id === currentPlan ? 'Current Plan' : 
                 plan.academic ? 'Verify Student Status' :
                 plan.id === 'free' ? 'Current Plan' :
                 'Upgrade Now'}
                {plan.id !== currentPlan && <ArrowRight className="ml-2 h-4 w-4" />}
              </Button>
            </div>
          ))}
        </div>
      </div>

      {/* Billing */}
      {currentPlan !== 'free' && (
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <h3 className="font-semibold text-gray-900 mb-4">Billing</h3>
          <div className="space-y-4">
            <div className="flex justify-between">
              <span className="text-gray-600">Next billing date:</span>
              <span className="text-gray-900">March 20, 2024</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Payment method:</span>
              <span className="text-gray-900">•••• •••• •••• 1234</span>
            </div>
            <div className="pt-4 border-t border-gray-200">
              <Button variant="outline" size="sm">
                Update Payment Method
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}